package com.daily.taskcenter.config;

import com.daily.taskcenter.anno.RegisterTask;
import com.daily.taskcenter.entity.DynamicTaskLog;
import com.daily.taskcenter.service.IDynamicTaskLogService;
import com.daily.taskcenter.tasks.ReturnT;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author qinchen
 * @date 2021/5/17 20:42
 * @description TODO
 */
@Slf4j
@Aspect
@Component
public class DyTaskAspect {

    public static final int STATUS_OK = 1;

    /**
     * 后面可以考虑一个功能操作可 对应 多个事件处理器
     */
    private Map<String, String> beforeEvents = new HashMap<>();
    private Map<String, String> afterEvents = new HashMap<>();

    @Autowired
    private IDynamicTaskLogService dynamicTaskLogService;

    @Value("${server.role:}")
    public String serverRole;

    @Around("@annotation(registerTask)")
    public Object around(ProceedingJoinPoint joinPoint, RegisterTask registerTask) throws Throwable {

        // 此处判断主从集群，如果是主节点，则执行，否则不做任何操作
        if(!"master".equals(serverRole)) {
            log.info("非主节点，不执行任务");
            return null;
        }

        Object[] args = joinPoint.getArgs();

        String taskName = registerTask.name();

        Object aThis = joinPoint.getTarget();
        String excuteClassName = aThis.getClass().getSimpleName();
        log.info("定时任务{}, 执行器 = {} 开始执行", taskName, excuteClassName);
        long begin = System.currentTimeMillis();

        // 执行业务逻辑
        Object proceed = null;
        try {
            proceed = joinPoint.proceed(args);
        } catch (Exception e) {
            log.error("执行器内部逻辑发生异常", e);
        }

        long end = System.currentTimeMillis();
        log.info("定时任务{}, 执行器 = {} 执行完毕，耗时 {} ms", taskName, excuteClassName, (end - begin));

        DynamicTaskLog dynamicTaskLog = new DynamicTaskLog();
        dynamicTaskLog.setTaskName(taskName);
        dynamicTaskLog.setTaskClass(excuteClassName);

        InetAddress inetAddress = InetAddress.getLocalHost();
        String hostAddress = inetAddress.getHostAddress();

        if (null != proceed) {
            ReturnT result = (ReturnT) proceed;
            dynamicTaskLog.setStatus(result.getCode());
        } else {
            dynamicTaskLog.setStatus(ReturnT.FAIL_CODE);
        }

        dynamicTaskLog.setExecHost(hostAddress);
        dynamicTaskLog.setExecTime(end - begin);
        dynamicTaskLog.setCreateTime(new Date());
        dynamicTaskLog.setUpdateTime(new Date());

        dynamicTaskLogService.save(dynamicTaskLog);

        return proceed;
    }

}
